<?php
/**
 * 活动
 */
namespace app\common\model;
use think\Model;
use app\admin\model\CharitableClass as CharitableClassModel;

class CharitableArticle extends Model
{
    protected $name = 'charitable_article';

    /**
     * 查询该活动详情
     * @param $id   活动ID
     * @return CharitableArticle|array|false|mixed|Model|null
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public static function getDetails($id){
        $data = self::where('id',$id)->find();
        if(!empty($data)){
            $class = CharitableClassModel::getDetails($data['cid']);
            $data['class_name'] = $class['title'];
            $data['content'] = htmlspecialchars_decode($data['content']);   //反向转义
            return $data;
        }
        return false;
    }

    /**
     * API查看该活动详情 浏览+1
     * @param $id
     * @return CharitableArticle|array|false|mixed|Model|null
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public static function apiGetDetails($id){
        self::where(['id'=>$id])->inc('browse',1)->update();
        return self::getDetails($id);
    }

    /**
     * 修改文章
     * @param $id   文章ID
     * @param $data 文章内容
     * @return bool
     */
    public static function edit($id,$data){
        $data['update_time'] = date('Y-m-d H:i:s',time());
        self::startTrans();
        try {
            self::where('id',$id)->update($data);
            self::commit();
            return true;
        } catch (HttpException $e){
            self::rollback();
            return false;
        }

    }

}